import React, { Component } from 'react'
import { connect } from 'dva';
import { Radio, Form, Modal } from 'antd';
import router from 'umi/router';
import AntdForm from '@/components/AntdForm';
import AdButton from '@/components/AdButton';
import AntdFormItem from '@/components/AntdFormItem';
import AntdInput from '@/components/AntdInput';
import FileReader from '@/components/FileReader';
import {
    formItemFragement,
    allAddFile,
    filterDeteteFile,
} from '@/utils/common';
import { selectOcrList, doubleArr, routeUrl, ocrCompanyList, ocrVDList, fieldsForm, codes, onlyUploadPaper } from './utils';
import styles from './index.less';
import { allDispatchType, selectDetail } from './utils';
const confirm = Modal.confirm;

@Form.create()
@connect(({ paperVerify }) => ({
    ocrDetails: paperVerify.ocrDetails,
    ocrPapersDetail: paperVerify.ocrPapersDetail
}))
export default class OcrPaperDetailInfo extends Component {
    constructor(props) {
        super(props)
        this.state = {
            update: false,
            uploadLoading: false
        }
    }
    onChange = e => {
        const { setLastStateChange } = this.props;
        setLastStateChange([{ papersType: e.target.value }]);
    };
    paperTypeDom = (typeList) => {
        const { papersId, papersType, ocrId, alreadyAddPaper } = this.props;
        return <Radio.Group onChange={this.onChange} value={papersType} disabled={papersId}>
            {
                typeList && typeList.map((v) => <Radio
                    value={v.code}
                    disabled={alreadyAddPaper && alreadyAddPaper.indexOf(v.code) > -1}
                >{v.value}</Radio>)
            }
        </Radio.Group>
    }
    uploadPaper = () => {
        const { setLastStateChange } = this.props;
        setLastStateChange([{ showUpload: true }]);
    }
    //证件详情： 
    getOcrPapersDetail = (id) => {
        const newId = id;
        const { setLastStateChange } = this.props;
        selectDetail({
            type: allDispatchType.ocrPapersInfo,
            payload: { id: newId },
            props: this.props,
            callback: (data) => {
                setLastStateChange([{ showUpload: false }]);
            }
        })
    }
    //证件识别
    discernPaper = (flag) => {
        const { form, papersType, ocrId, papersId } = this.props;
        form.validateFieldsAndScroll((errors, values) => {
            const { attaQuantity, attaQuantityBack } = values;
            let params = {
                ocrId,
                type: papersType
            }
            if (papersId) params.id = papersId;
            let fileTokens = [];
            if (attaQuantity) {
                fileTokens.push(...allAddFile(attaQuantity));
            }
            if (attaQuantityBack) {
                fileTokens.push(...allAddFile(attaQuantityBack));
            }
            params.fileTokens = fileTokens;
            //证件识别后，返回证件识别信息：data.result                                                                                                                                                                                                                              
            this.dispatchCall('discern', params, flag)
        });

    }
    //保存证件：
    saveData = (flag) => {
        const { form, papersType, ocrId, papersId } = this.props;
        form.validateFieldsAndScroll((errors, values) => {
            const { attaQuantity, ...param } = values;
            let params = {
                id: papersId,
                ocrId,
                papersType,
                papersInfo: JSON.stringify(param)
            }
            this.dispatchCall('savePaper', params, true)
        });
    }
    //删除证件：
    delOcrPaper = () => {
        const { papersId } = this.props;
        confirm({
            title: '确定要删除这条数据吗？',
            content: ' ',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk: () => {
                this.dispatchCall('delOcrPapers', { id: papersId }, true);
            },
        });
    };
    uploadCallback = (val) => {
        this.setState({
            uploadLoading: val
        })
    }

    dispatchCall = (type, params, flag) => {
        const { addMode, papersId, setInfoModal, dispatch, setLastStateChange, ocrId } = this.props;
        dispatch({
            type: allDispatchType[type],
            payload: params,
            callback: (data) => {
                if (flag || addMode) setInfoModal();
                selectOcrList({ props: this.props });
                setLastStateChange([{ showUpload: false, papersId: data && data.papersId ? data.papersId : papersId }]);

                if (addMode) {
                    router.push(`${routeUrl.detail}/${data.ocrId}`);
                } else {
                    if (ocrId) {
                        selectDetail({
                            type: allDispatchType.detail,
                            payload: { id: ocrId },
                            props: this.props
                        })
                    }
                    this.setState((pre) => ({
                        update: !pre.update
                    }))
                    data && this.props.form.setFieldsValue({ files: data.fileList || [] });
                }


            }
        })
    }

    render() {
        const { uploadLoading } = this.state;
        const { ocrDetails, ocrId, papersId, ocrPapersDetail, showUpload, form: { getFieldDecorator }, ocrType, papersType, disabled } = this.props;
        const typeList = ocrType === 'COMPANY' ? ocrCompanyList : ocrVDList;
        const details = papersId ? ocrPapersDetail : {};
        const newFieldsForm = papersType ? fieldsForm[papersType] : fieldsForm['BUSINESS_LICENSE']
        const commonParams = {
            getFieldDecorator,
        };

        const onlyUpload = onlyUploadPaper.indexOf(papersType) > -1 ? true : false;
        const isUpload = details && !showUpload ? false : true;
        const ocrDetail = ocrDetails[ocrId] || {};
        const uploadForm = [
            <span className={styles.paperImages}>
                <AntdFormItem
                    label="图片"
                    code="attaQuantity"
                    initialValue={details.fileList || []}
                    rules={[{
                        required: disabled ? false : showUpload || onlyUpload
                    }]}
                    {...commonParams}
                    style={{ marginBottom: '40px' }}
                >
                    <FileReader urlType="tms" disabled={disabled}
                        showUpload={disabled ? false : isUpload || onlyUpload}
                        fileLength={onlyUpload ? 10 : 1}
                        callback={this.uploadCallback}
                    />
                </AntdFormItem>,
            </span>
        ]
        let upluadDom = [
            uploadForm
        ]
        if (doubleArr.indexOf(papersType) > -1) {
            upluadDom = [
                [
                    <span className={styles.paperImages}>
                        <AntdFormItem
                            label="正面"
                            code="attaQuantity"
                            rules={[{ required: true }]}
                            initialValue={details.fileList && details.fileList[0] ? [details.fileList[0]] || [] : []}
                            {...commonParams}
                        >
                            <FileReader urlType="tms" disabled={disabled}
                                showUpload={isUpload}
                                fileLength={1}
                                callback={this.uploadCallback}
                            />
                        </AntdFormItem>
                    </span>],
                [
                    <span className={styles.paperImages}>
                        <AntdFormItem
                            label="反面"
                            code="attaQuantityBack"
                            initialValue={details.fileList && details.fileList[1] ? [details.fileList[1]] || [] : []}
                            {...commonParams}
                        >
                            <FileReader urlType="tms" disabled={disabled}
                                showUpload={isUpload}
                                fileLength={1}
                                callback={this.uploadCallback}
                            />
                        </AntdFormItem>
                    </span>,
                ]
            ]
        }
        const formItemDom = () => {

            let arr = []
            const detail = details ? details.result : {}
            newFieldsForm && newFieldsForm.map((v, index) => {
                arr.push(
                    [
                        <AntdFormItem
                            label={v.value}
                            // rules={[{ required: true }]}
                            code={v.key}
                            initialValue={detail ? detail[v.key] : ''}
                            {...commonParams}
                            key={v.key + '_' + index}
                        >
                            <AntdInput disabled={disabled} />
                        </AntdFormItem>
                    ]
                )
            })

            arr.push([
                <span className={styles.paperFormImages}>
                    <AntdFormItem
                        label="图片"
                        code="files"
                        initialValue={details.fileList || []}
                        {...commonParams} >
                        <FileReader urlType="tms"
                            showUpload={false}
                        />
                    </AntdFormItem>
                </span>
            ]);
            return arr
        }
        return (
            <div className={styles.cus_tableListForm}>
                {
                    typeList && typeList && this.paperTypeDom(typeList)
                }
                {
                    showUpload || onlyUpload ?
                        <div>
                            <AntdForm>{formItemFragement(upluadDom)}</AntdForm>
                            {!disabled &&
                                <div className={styles.page_bottom_btn}>
                                    {
                                        onlyUpload && papersId &&
                                        <AdButton code={codes.paperDel} text="删除" type="danger" ghost onClick={() => this.delOcrPaper()}></AdButton>
                                    }
                                    <AdButton loading={uploadLoading} code={codes.discernPaper} text="保存" type="primary" onClick={() => this.discernPaper(onlyUpload)}></AdButton>
                                </div>
                            }
                        </div>
                        :
                        <div>
                            <AntdForm>{formItemFragement(formItemDom())}</AntdForm>
                            {!disabled && <div className={styles.page_bottom_btn}>
                                <AdButton code={codes.paperDel} text="删除" type="danger"
                                    ghost onClick={() => this.delOcrPaper()}></AdButton>
                                <AdButton text="重新上传" type="primary" onClick={() => this.uploadPaper()}></AdButton>
                                <AdButton code={codes.paperEdit} text="保存" type="primary" onClick={() => this.saveData()}></AdButton>
                            </div>}
                        </div>
                }
            </div>
        )
    }
}
